import React, { useEffect, useState, useRef } from 'react';
import { Dialog, Form, Input, Select, Switch, Button, MessagePlugin, Textarea, DatePicker } from 'tdesign-react';
import { JupiterArticle, JupiterArticleForm } from '../../../types/articleTypes';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { uploadImage } from '../../../services/uploadService';
import DictionarySelect from '../../../components/Dictionary/DictionarySelect';
import CoverImageUpload from '../../../components/Article/CoverImageUpload';
import '@wangeditor/editor/dist/css/style.css';

interface ArticleFormProps {
    visible: boolean;
    title: string;
    editingData?: Partial<JupiterArticle>;
    onClose: () => void;
    onSubmit: (data: JupiterArticleForm) => void;
}

export default function ArticleForm({ visible, title, editingData, onClose, onSubmit }: ArticleFormProps) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    
    // 富文本编辑器相关状态
    const [editor, setEditor] = useState<IDomEditor | null>(null);
    const [html, setHtml] = useState('');
    const editorRef = useRef<IDomEditor | null>(null);

    // 编辑器配置
    const editorConfig: Partial<IEditorConfig> = {
        placeholder: '请输入文章内容...',
        onChange: (editor: IDomEditor) => {
            const htmlContent = editor.getHtml();
            setHtml(htmlContent);
            form.setFieldsValue({ content: htmlContent });
        },
        MENU_CONF: {
            // 配置图片上传
            uploadImage: {
                // 上传接口
                server: '/api/upload/image',
                // 字段名
                fieldName: 'file',
                // 最大文件大小 5M
                maxFileSize: 5 * 1024 * 1024,
                // 允许的文件类型
                allowedFileTypes: ['image/*'],
                // 自定义上传
                customUpload: async (file: File, insertFn: Function) => {
                    try {
                        const response = await uploadImage(file);
                        
                        if (response.code === 200) {
                            // 插入图片到编辑器
                            insertFn(response.data.url, response.data.alt || '', response.data.href || '');
                        } else {
                            MessagePlugin.error(response.message || '图片上传失败');
                        }
                    } catch (error) {
                        console.error('图片上传失败:', error);
                        MessagePlugin.error('图片上传失败');
                    }
                },
                // 上传前的钩子
                onBeforeUpload: (file: File) => {
                    // 检查文件大小
                    if (file.size > 5 * 1024 * 1024) {
                        MessagePlugin.error('图片大小不能超过5MB');
                        return false;
                    }
                    return true;
                },
                // 上传进度
                onProgress: (progress: number) => {
                    console.log('上传进度:', progress);
                },
                // 上传成功
                onSuccess: (file: File, res: any) => {
                    console.log('上传成功:', res);
                },
                // 上传失败
                onFailed: (file: File, res: any) => {
                    console.error('上传失败:', res);
                    MessagePlugin.error('图片上传失败');
                },
            },
        },
    };

    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {
        excludeKeys: [
            'group-video',
            'group-more-style',
        ],
    };

    useEffect(() => {
        if (visible) {
            if (editingData) {
                form.setFieldsValue({
                    title: editingData.title,
                    summary: editingData.summary,
                    author: editingData.author,
                    categoryUuid: editingData.categoryUuid,
                    tagUuids: editingData.tagUuids || [],
                    status: editingData.status || 'DRAFT',
                    isTop: editingData.isTop || false,
                    publishTime: editingData.publishTime,
                    cover: editingData.cover,
                    readType: editingData.readType || 0,
                    isOriginal: editingData.isOriginal !== false,
                    isCarousel: editingData.isCarousel || false,
                    isRecommend: editingData.isRecommend || false,
                    originalUrl: editingData.originalUrl,
                });
                // 设置富文本编辑器内容
                const content = editingData.content || '';
                setHtml(content);
                form.setFieldsValue({ content });
            } else {
                form.reset();
                form.setFieldsValue({
                    status: 'DRAFT',
                    isTop: false,
                    readType: 0,
                    isOriginal: true,
                    isCarousel: false,
                    isRecommend: false,
                });
                // 清空富文本编辑器内容
                setHtml('');
                form.setFieldsValue({ content: '' });
            }
        }
    }, [visible, editingData, form]);

    // 编辑器创建完成
    const handleCreated = (editor: IDomEditor) => {
        editorRef.current = editor;
        setEditor(editor);
    };

    // 组件销毁时清理编辑器
    useEffect(() => {
        return () => {
            if (editorRef.current == null) return;
            editorRef.current.destroy();
        };
    }, []);

    const handleSubmit = async () => {
        try {
            const result = await form.validate();
            if (result === true) {
                setLoading(true);
                const formData = form.getFieldsValue(true);
                onSubmit(formData as JupiterArticleForm);
            }
        } catch (error) {
            console.error('表单验证失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleCancel = () => {
        form.reset();
        setHtml('');
        form.setFieldsValue({ content: '' });
        onClose();
    };

    return (
        <Dialog
            header={title}
            visible={visible}
            width={1200}
            onClose={handleCancel}
            footer={
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                    <Button theme="default" onClick={handleCancel}>
                        取消
                    </Button>
                    <Button theme="primary" loading={loading} onClick={handleSubmit}>
                        确定
                    </Button>
                </div>
            }
        >
            <Form
                form={form}
                labelWidth={100}
                layout="vertical"
            >
                <div style={{ display: 'flex', gap: 20 }}>
                    <Form.FormItem
                        label="文章标题"
                        name="title"
                        rules={[
                            { required: true, message: '请输入文章标题' },
                            { max: 200, message: '标题不能超过200个字符' }
                        ]}
                        style={{ flex: 2 }}
                    >
                        <Input placeholder="请输入文章标题" />
                    </Form.FormItem>

                    <Form.FormItem
                        label="作者"
                        name="author"
                        rules={[
                            { required: true, message: '请输入作者' },
                            { max: 50, message: '作者不能超过50个字符' }
                        ]}
                        style={{ flex: 1 }}
                    >
                        <Input placeholder="请输入作者" />
                    </Form.FormItem>
                </div>

                <Form.FormItem
                    label="文章封面"
                    name="cover"
                >
                    <CoverImageUpload placeholder="请输入封面图URL或上传图片" />
                </Form.FormItem>

                <Form.FormItem
                    label="文章摘要"
                    name="summary"
                    rules={[{ max: 500, message: '摘要不能超过500个字符' }]}
                >
                    <Textarea
                        placeholder="请输入文章摘要"
                        rows={3}
                    />
                </Form.FormItem>

                <Form.FormItem
                    label="文章内容"
                    name="content"
                    rules={[
                        { required: true, message: '请输入文章内容' }
                    ]}
                >
                    <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                        <Toolbar
                            editor={editor}
                            defaultConfig={toolbarConfig}
                            mode="default"
                            style={{ borderBottom: '1px solid #ccc' }}
                        />
                        <Editor
                            defaultConfig={editorConfig}
                            value={html}
                            onCreated={handleCreated}
                            onChange={(editor) => {
                                const htmlContent = editor.getHtml();
                                setHtml(htmlContent);
                                form.setFieldsValue({ content: htmlContent });
                            }}
                            mode="default"
                            style={{ height: '400px', overflowY: 'hidden' }}
                        />
                    </div>
                </Form.FormItem>

                <div style={{ display: 'flex', gap: 20 }}>
                    <Form.FormItem
                        label="分类"
                        name="categoryUuid"
                        style={{ flex: 1 }}
                    >
                        <Select
                            placeholder="请选择分类"
                            // TODO: 需要从分类服务获取选项
                            options={[]}
                            filterable
                        />
                    </Form.FormItem>

                    <Form.FormItem
                        label="标签"
                        name="tagUuids"
                        style={{ flex: 1 }}
                    >
                        <Select
                            placeholder="请选择标签"
                            multiple
                            // TODO: 需要从标签服务获取选项
                            options={[]}
                            filterable
                        />
                    </Form.FormItem>
                </div>

                {/* 分隔线 */}
                <div style={{ borderTop: '1px solid #e7e7e7', margin: '20px 0', paddingTop: '20px' }}>
                    <h4 style={{ margin: '0 0 16px 0', color: '#333', fontSize: '14px', fontWeight: '500' }}>发布设置</h4>
                </div>

                <Form.FormItem
                    label="发布时间"
                    name="publishTime"
                >
                    <DatePicker
                        placeholder="请选择发布时间"
                        enableTimePicker
                        format="YYYY-MM-DD HH:mm:ss"
                    />
                </Form.FormItem>

                {/* 状态和权限设置 */}
                <div style={{ display: 'flex', gap: 20, marginBottom: 16 }}>
                    <Form.FormItem
                        label="发布状态"
                        name="status"
                        rules={[{ required: true, message: '请选择状态' }]}
                        style={{ flex: 1 }}
                    >
                        <DictionarySelect
                            dictType="article_status"
                            placeholder="请选择状态"
                            clearable={false}
                        />
                    </Form.FormItem>

                    <Form.FormItem
                        label="阅读权限"
                        name="readType"
                        style={{ flex: 1 }}
                    >
                        <DictionarySelect
                            dictType="article_read_type"
                            placeholder="请选择阅读权限"
                            clearable={false}
                        />
                    </Form.FormItem>
                </div>

                {/* 展示设置 */}
                <div style={{ marginBottom: 16 }}>
                    <h4 style={{ margin: '0 0 12px 0', color: '#333', fontSize: '14px', fontWeight: '500' }}>展示设置</h4>
                    <div style={{ display: 'flex', gap: 20 }}>
                    <Form.FormItem
                        label="置顶"
                        name="isTop"
                        style={{ flex: 1 }}
                    >
                        <Switch />
                    </Form.FormItem>

                    <Form.FormItem
                        label="原创"
                        name="isOriginal"
                        style={{ flex: 1 }}
                    >
                        <Switch />
                    </Form.FormItem>

                    <Form.FormItem
                        label="轮播展示"
                        name="isCarousel"
                        style={{ flex: 1 }}
                    >
                        <Switch />
                    </Form.FormItem>

                    <Form.FormItem
                        label="推荐展示"
                        name="isRecommend"
                        style={{ flex: 1 }}
                    >
                        <Switch />
                    </Form.FormItem>
                    </div>
                </div>

                <Form.FormItem
                    label="转载原文地址"
                    name="originalUrl"
                >
                    <Input placeholder="如果是转载文章，请输入原文地址" />
                </Form.FormItem>
            </Form>
        </Dialog>
    );
}